'use strict';

const defaultTypes = ['PENDING', 'FULFILLED', 'REJECTED', 'ERROR'];

function isPromise(value) {
	if (value !== null && typeof value === 'object') {
		return value.promise && typeof value.promise.then === 'function';
	}
}

export default function promiseMiddleware(config = {}) {
	return next => action => {
		const promiseTypeSuffixes = config.promiseTypeSuffixes || defaultTypes;

		if (!isPromise(action.payload)) {
			return next(action);
		}

		const {
			type, 
			payload, 
			meta
		} = action;
		const {
			promise, 
			data, 
			onError, 
			onSuccess, 
			onFinish
		} = payload;

		const [PENDING, FULFILLED, REJECTED, ERROR] = (meta || {}).promiseTypeSuffixes || promiseTypeSuffixes;

		next({
			type: `${type}_${PENDING}`,
			payload: data,
			meta
		});

		return promise.then(
			payload => {
				next({
					payload: payload,
					type: `${type}_${FULFILLED}`,
					meta,
					onError,
					onSuccess,
					onFinish
				})
			},
			error => next({
				payload: error,
				error: true,
				type: `${type}_${REJECTED}`,
				meta,
				onError,
				onFinish
			})
		);

	}
}